package com.qf.lanzhou.blog.api.controller;

import com.qf.lanzhou.blog.api.pojo.entity.Collect;
import com.qf.lanzhou.blog.api.pojo.entity.User;
import com.qf.lanzhou.blog.api.service.CollectService;
import com.qf.lanzhou.blog.api.service.impl.CollectServiceimpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author jian   添加收藏方法
 * @Date 2020/12/17 15:32
 * @JDK 1.8
 * @Version 1.0
 */
@WebServlet("/collect.do")
public class CollectServlet extends BaseServletPost{
    private CollectService collectService=new CollectServiceimpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决请求的乱码
        req.setCharacterEncoding("utf-8");
        //解决响应乱码
        resp.setContentType("text/html;charset=utf-8");

        //判断用户是否有登录
        User user =(User) req.getSession().getAttribute("user");
        if(user==null){
            //作用域没有用户信息,返回登录页面
             failedResultWrite("未登录",resp);
        }

        //获取参数
        User user1 = (User) req.getSession().getAttribute("user");
        Long id = user1.getId();
        //转为string类型
        String userId = id + "";
        String articleId = req.getParameter("articleId");
        String collectStatus = req.getParameter("collectStatus");
        //查询文章是否已经收藏,返回集合
        List<Collect> list=collectService.select(userId,articleId,collectStatus);
        if (list==null){
            collectService.insert(userId,articleId,collectStatus);
            failedResultWrite("收藏成功",resp);
            return ;

        }
        for (int j = 0; j<list.size() ; j++) {
            Collect collect = list.get(j);
            System.out.println(collect);

            if(userId.equals(collect.getUserId())&&articleId.equals(collect.getArticleId())&&collectStatus.equals(collect.getCollectStatus())){
                resp.getWriter().write("已收藏过");
                return;
            }
        }
        int i = collectService.insert(userId,articleId,collectStatus);
        if(i==1){
            successResultWrite("收藏成功",resp);
        }

    }
}
